import { zoomApi } from './zoomApi';

const zoomClientApp = kintone.app.getRelatedRecordsTargetAppId("relatedZoomClientId");
const hostRole = 1;
const attendRole = 0;
const userId = ''; //'VFo_-1LbSWOrSonMH9S2cA';
const zoomapi = new zoomApi();
const meetingType = 2;

kintone.events.on('app.record.detail.show', event => {
    let zoomApp = kintone.app.getId();
    let record = event.record;
    let recordId = event.record['recordId'].value;

    if (document.getElementById('join') !== null) {
        return;
    }
    let loginUser = kintone.getLoginUser();

    let addZoomDom = zoomClientUrl => {
        if (document.getElementById('zoom') !== null) {
            document.getElementById('zoom').remove();
        }
        let zoomDiv = document.createElement("div");
        let zoom = `<div id="zoom"><iframe style="border:none; height: 600px; width: 100%;" src= ${zoomClientUrl} 
            sandbox="allow-forms allow-scripts allow-same-origin" allow="microphone; camera"></iframe></div`;
        zoomDiv.innerHTML = zoom;
        kintone.app.record.getSpaceElement('zoom').appendChild(zoomDiv);
    }

    let getZoomClientId = () => {
        let params = {
            app: zoomClientApp,
            query: `CalendarId = ${recordId} limit 1`
        };
        return kintone.api(kintone.api.url('/k/v1/records', true), 'GET', params).then(resp => {
            let records = resp.records;
            if (records.length > 0) {
                return records[0]['$id'].value;
            }
            return false
        }
        );
    }

    let updateZoomClient = addParams => {
        return kintone.api(kintone.api.url('/k/v1/record', true), 'PUT', addParams);
    }

    let addZoomClient = updateParams => {
        return kintone.api(kintone.api.url('/k/v1/record', true), 'POST', updateParams).then(resp => {
            return resp["id"];
        });
    }

    let updateHost = () => {
        let params = {
            "app": zoomApp,
            "id": kintone.app.record.getId(),
            "record": {
                "Host": {
                    "value": [
                        {
                            "code": loginUser.code
                        }
                    ]
                }
            }
        };
        kintone.api(kintone.api.url('/k/v1/record', true), 'PUT', params);
    }

    let zoom = {
        init: function () {
            this.addHost();
            this.addJoin();
        },
        addHost() {
            let hostButton = document.createElement('button');
            hostButton.id = 'host';
            hostButton.innerText = 'Host';
            hostButton.className = 'btn btn-primary';
            kintone.app.record.getSpaceElement('join').appendChild(hostButton);

            hostButton.onclick = () => {
                updateHost();
                getZoomClientId().then(resp => {
                    let updateParams = {
                        "app": zoomClientApp,
                        "record": {
                            "meetingNumber": {
                                "value": record.meetingNumber.value
                            },
                            "password": {
                                "value": record.password.value
                            },
                            "name": {
                                "value": loginUser.name
                            },
                            "role": {
                                "value": hostRole
                            },
                            'CalendarId': {
                                "value": recordId
                            }
                        }
                    }
                    if (resp) {
                        updateParams.id = resp;
                        updateZoomClient(updateParams).then(() => {
                            let zoomClientUrl = `/k/${zoomClientApp}/show#record=${updateParams.id}`;
                            addZoomDom(zoomClientUrl);
                        });
                    }
                    else {
                        addZoomClient(updateParams).then(resp => {
                            let zoomClientUrl = `/k/${zoomClientApp}/show#record=${resp}`;
                            addZoomDom(zoomClientUrl);
                        });
                    }
                })
            };
        },
        addJoin() {
            let joinButton = document.createElement('button');
            joinButton.id = 'attend';
            joinButton.innerText = 'Attend';
            joinButton.className = 'btn btn-info';
            joinButton.setAttribute('style', 'margin-left:10px;');
            kintone.app.record.getSpaceElement('join').appendChild(joinButton);

            joinButton.onclick = () => {
                getZoomClientId().then(resp => {
                    if (!resp) {
                        alert("Please wait for the Host");
                    }
                    else {
                        let updateParams = {
                            "app": zoomClientApp,
                            "id": resp,
                            "record": {
                                "role": {
                                    "value": attendRole
                                }
                            }
                        }
                        updateZoomClient(updateParams).then(() => {
                            let zoomClientUrl = `/k/${zoomClientApp}/show#record=${updateParams.id}`;
                            addZoomDom(zoomClientUrl)
                        });
                    }
                })
            };
        }
    }
    zoom.init();
});

kintone.events.on('app.record.create.submit', event => {
    let record = event.record;
    let data = {
        "topic": record.topic.value,
        "type": meetingType,
        "start_time": record.start_time.value,
        "duration": record.duration.value
    };

    return zoomapi.createMeeting(userId, data).then(args => {
        if (userId === '') return;
        let resp = JSON.parse(args[0]);
        record['meetingNumber']['value'] = resp.id;
        record['join_url']['value'] = resp.join_url;
        record['password']['value'] = resp.encrypted_password;
        return event;
    }, error => {
        console.log(error);
    });
});

kintone.events.on(['app.record.create.show', 'app.record.index.edit.show', 'app.record.edit.show'], event => {
    let record = event.record;
    record['meetingNumber']['disabled'] = true;
    record['password']['disabled'] = true;
    record['join_url']['disabled'] = true;
    return event;
});

kintone.events.on(['app.record.detail.delete.submit', 'app.record.index.delete.submit'], event => {
    let record = event.record;
    let meetingId = Number(record.meetingNumber.value);
    return zoomapi.deleteMeeting(meetingId).then(args => {
        if (args[1] !== 204) alert("update to zoom failed");
        return event;
    }, error => {
        console.log(error);
    });
});


